package com.naiyumi.action;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.naiyumi.model.UserInfo;
import com.naiyumi.service.LoginService;
import com.opensymphony.xwork2.ActionContext;

@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private LoginService loginService;

	private String loginName;
	private String loginPassword;

	public String execute() {
		return "input";
	}

	public String logout() {
		ActionContext.getContext().getSession().clear();
		return "input";
	}

	public String login() {
		logger.info("初始化登录页面.....");
		String loginName = this.getLoginName().trim();
		String loginPassword = this.getLoginPassword().trim();
		UserInfo userInfo = this.loginService.checkLogin(loginName,
				loginPassword);
		if (userInfo == null) {
			this.addFieldError("loginError", "账号或密码错误!");// 定义在username上面提示错误信息
			return "failer";
		}
		ActionContext.getContext().getSession().put("userId", userInfo.getUserId());
		ActionContext.getContext().getSession().put("loginName", this.getLoginName());
		ActionContext.getContext().getSession().put("admin", userInfo.isAdmin());
		ActionContext.getContext().getSession().put("userInfo", userInfo);
		logger.info("工号：" + userInfo.getUserId() + "于" + "" + "登录系统成功。");
		return "success";
	}

	@Override
	public void validate() {
		//执行execute()之前会执行此方法
//		if (null == this.getLoginName()
//				|| "".equals(this.getLoginName().trim())) {
//			this.addFieldError("username", "username error");// 添加错误信息
//		}
//		if (null == this.getLoginPassword()
//				|| "".equals(this.getLoginPassword().trim())) {
//			this.addFieldError("password", "password error");// 添加错误信息
//		}
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getLoginPassword() {
		return loginPassword;
	}

	public void setLoginPassword(String loginPassword) {
		this.loginPassword = loginPassword;
	}

}
